/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:lmrp-webapp
 * Create Time: 2016年4月13日 上午11:26:29
 */
package com.lenovo.lmrp.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.google.gson.Gson;
import com.lenovo.lmrp.api.eventrecorder.ITicketStatisticsQuery;
import com.lenovo.lmrp.api.itsmgateway.IItsmProject;
import com.lenovo.lmrp.api.itsmgateway.IItsmTicket;
import com.lenovo.lmrp.api.model.RestResponse;
import com.lenovo.lmrp.api.model.entity.CitygpsPO;
import com.lenovo.lmrp.api.model.entity.ProjectPO;
import com.lenovo.lmrp.api.model.view.MapStatisticsVO;
import com.lenovo.lmrp.api.model.view.PageVO;
import com.lenovo.lmrp.api.model.view.ProjectVO;
import com.lenovo.lmrp.util.RestClientFactory;
import com.lenovo.sdc.framework.common.base.BaseRestSpringController;
import com.lenovo.sdc.framework.rest.RestClientProxy;
import com.lenovo.sdc.framework.util.PageData;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * 
 * @author zx-lxj
 * @version $Id: MapContorller.java, v 0.1 2016年4月13日 上午11:26:29 zx-lxj Exp $
 */

@Controller
public class MapContorller extends BaseRestSpringController{
    /** binder用于bean属性的设置 */
    @InitBinder  
    public void initBinder(WebDataBinder binder) {  
            binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));  
    }
       
    /**
     * 增加了@ModelAttribute的方法可以在本controller方法调用前执行,可以存放一些共享变量,如枚举值,或是一些初始化操作
     */
    @ModelAttribute
    public void init(ModelMap model) {
        model.put("now", new java.sql.Timestamp(System.currentTimeMillis()));
    }

    @Autowired
    RestClientFactory restClientFactory = new RestClientFactory();
    
    /**
     * 请求跳转地图页面
     * @author zx-lxj
     * @return 视图页面/WEB-INF/view/map.html
     * @throws Exception
     */
    @RequestMapping(value="/showmap")
    public String showMap() throws Exception {
        return "/map";
    }
    
    /**
     * 内部类
     * @author zx-lxj
     * @version $Id: MapContorller.java, v 0.1 2016年4月15日 下午11:27:21 zx-lxj Exp $
     */
    @JsonAutoDetect(fieldVisibility = Visibility.ANY)
    private class projectNames {
        String text;
        String value;
        public projectNames(String text, String value) {
            this.text = text;
            this.value = value;
        }
    }
    
    @JsonAutoDetect(fieldVisibility = Visibility.ANY)
    private class citys {
        String text;
        String value;
        String point;
        public citys(String text, String value,String point) {
            this.text = text;
            this.value = value;
            this.point = point;
        }
    }
    
    @JsonAutoDetect(fieldVisibility = Visibility.ANY)
    private class mapList {
        Map<String, Object> point;
        String city;
        int count;
        public mapList(Map<String, Object> point,String city,int count) {
            this.point = point;
            this.city = city;
            this.count = count;
        }
    }
    
    @JsonAutoDetect(fieldVisibility = Visibility.ANY)
    private class mapdata {
        int sun;
        List list = new ArrayList();
        public mapdata(int sun, List list) {
            this.sun = sun;
            this.list = list;
        }
    }
    
    /**
     * 查询项目名称列表  http://localhost:9000/springmvc/xihe/map/projects
     * @author zx-lxj
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{itsmcode}/map/projects",method=RequestMethod.GET)
    @ResponseBody
    public List<projectNames> getProjectNames(@PathVariable String itsmcode){
        final int MIN_VALUE = 2147483647;
        HashMap<String, String> scopes = new HashMap<String, String>();
        List<projectNames> projectList = new ArrayList<>();
        try{
            RestClientProxy itsmGatewayProxy = restClientFactory.getItsmGatewayClient();
            if(Objects.nonNull(itsmGatewayProxy)){
                IItsmProject iItsmProject = itsmGatewayProxy.getService(IItsmProject.class);
                if(Objects.nonNull(iItsmProject)){
                    RestResponse<PageData<ProjectPO>> listProject = iItsmProject.listProject(itsmcode, null, null, null, 0, MIN_VALUE);
                    if(Objects.nonNull(listProject)){
                        for(ProjectPO po : listProject.getResult().getPageData()){
                            projectList.add(new projectNames(po.getName(), po.getId() + "-" + po.getName()));
                        }   
                    }else{
                        log.error("error query project list is null");
                    }
                }else{
                    log.error("error no find IItsmProject.class ");
                }
            }else{
                log.error("error ItsmGatewayProxy interface exception");
            }
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }
        return projectList;
    }
    
    /**
     * 查询城市列表 http://localhost:9000/springmvc/xihe/map/citys
     * @author zx-lxj
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{itsmcode}/map/citys",method=RequestMethod.GET)
    @ResponseBody
    public List<citys> getCitys(@PathVariable String itsmcode){
        HashMap<String, String> scopes = new HashMap<String, String>();
        List<citys> citytList = new ArrayList<>();
        try{
            RestClientProxy eventRecorderProxy = restClientFactory.getEventRecorderClient();
            if(Objects.nonNull(eventRecorderProxy)){
                ITicketStatisticsQuery iTicketStatisticsQuery = eventRecorderProxy.getService(ITicketStatisticsQuery.class);
                if(Objects.nonNull(iTicketStatisticsQuery)){
                    RestResponse<List<CitygpsPO>> citygps = iTicketStatisticsQuery.getCityList(itsmcode);
                    if(Objects.nonNull(citygps)){
                        for(CitygpsPO po : citygps.getResult()){
                            citytList.add(new citys(po.getCity(),po.getCity(),"{"+po.getLongitude()+","+po.getLatitude()+"}"));
                        }
                    }else{
                        log.error("error query city list is null");
                    }
                }else{
                    log.error("error no find ITicketStatisticsQuery.class ");
                }
            }else{
                log.error("error EventRecorderProxy interface exception");
            }
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }
        return citytList;
    }
    
    /**
     * 按城市统计 http://localhost:9000/springmvc/xihe/map/citydata?project=变量&date=变量&city=变量
     * @param itsmcode
     * @param fields 查询条件集合  
     *      date 时间  "2016-01" 按月查  or "2016" 按年查
     *      project 项目名称  支持多个项目 逗号分隔     "itsm项目,联邦项目,..."
     *      city 选择的市名称   北京
     * @return
     */
    @RequestMapping(value="/{itsmcode}/map/citydata")
    @ResponseBody
    public List getCityData(ModelMap model,@PathVariable String itsmcode,@RequestParam("project") String project,@RequestParam("date") String date,@RequestParam("city") String city) throws Exception {
        HashMap<String, String> fields = new HashMap<String, String>();
        fields.put("period",date);
        fields.put("project",project);
        fields.put("city",city);
        List<MapStatisticsVO> mapList = new ArrayList<>();
        try{
            RestClientProxy eventRecorderProxy = restClientFactory.getEventRecorderClient();
            if(Objects.nonNull(eventRecorderProxy)){
                ITicketStatisticsQuery iTicketStatisticsQuery = eventRecorderProxy.getService(ITicketStatisticsQuery.class);
                if(Objects.nonNull(iTicketStatisticsQuery)){
                    RestResponse<List<MapStatisticsVO>> mapStatistics = iTicketStatisticsQuery.statisticsByCity(itsmcode,fields);
                    if(Objects.nonNull(mapStatistics)){
                        mapList =mapStatistics.getResult();
                      }else{
                          log.error("error query mapStatistics list is null");
                      }
                }else{
                   log.error("error no find ITicketStatisticsQuery.class ");
                }
            }else{
                log.error("error EventRecorderProxy interface exception");
            }
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }
        return mapList;
    }
    
    /**
     * 全国地图统计 http://localhost:9000/springmvc/xihe/map/mapdata?statisticstype=变量&project=变量&date=变量
     * @param itsmcode
     * @param statisticstype 统计数据类型 0 工单 1 门店  2 服务商 3 工程师
     * @param fields 查询条件
     *          date "2016-01" 按月查  or "2016" 按年查
     *          project 项目名称  支持多个项目 逗号分隔     "itsm项目,联邦项目,..."
     * @return
     */
    @RequestMapping(value="/{itsmcode}/map/mapdata")
    @ResponseBody
    public List getMapData(ModelMap model,@PathVariable String itsmcode,@RequestParam("statisticstype") Integer statisticstype,@RequestParam("project") String project,@RequestParam("date") String date) throws Exception {
        statisticstype = (statisticstype == null ? 0 : statisticstype);
        HashMap<String, String> fields = new HashMap<String, String>();
        HashMap<String, String> scopes = new HashMap<String, String>();
        List<mapList> mapCountList = new ArrayList<>();
        List<mapdata> mapdataList = new ArrayList<>();
        int sun = 0;
        fields.put("period",date);
        fields.put("project",project);
        log.info("project============"+project);
        try{
            RestClientProxy eventRecorderProxy = restClientFactory.getEventRecorderClient();
            if(Objects.nonNull(eventRecorderProxy)){
                ITicketStatisticsQuery iTicketStatisticsQuery = eventRecorderProxy.getService(ITicketStatisticsQuery.class);
                if(Objects.nonNull(iTicketStatisticsQuery)){
                    RestResponse<List<MapStatisticsVO>> mapStatistics = iTicketStatisticsQuery.statisticsByAll(itsmcode,statisticstype,fields);
                    if(Objects.nonNull(mapStatistics)){
                        for(MapStatisticsVO vo : mapStatistics.getResult()){
                            sun+=vo.getCount();
                            mapCountList.add(new mapList(vo.getPoint(),vo.getName(),vo.getCount()));
                        }
                        mapdataList.add(new mapdata(sun,mapCountList));
                    }else{
                        log.error("error query mapStatistics list is null");
                    }
                }else{
                    log.error("error no find ITicketStatisticsQuery.class ");
                }
            }else{
                log.error("error EventRecorderProxy interface exception");
            }    
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }
        return mapdataList;
    }
    
    /**
     * 按区域(经纬度)统计  http://localhost:9000/springmvc/xihe/map/regiondata?positionleft=变量&positionright=变量&statisticstype=变量&project=变量&date=变量
     * @param itsmcode 
     * @param fields
     *      date 时间  "2016-01"(by month) or "2016"(by year)
     *      project 项目名称  支持多个项目 逗号分隔     "itsm项目,联邦项目,..."
     *      positionleft 选择区域的左上角坐标  "经度,纬度" 不可以为空
     *      positionright 选择区域的右下角坐标 "经度,纬度" 不可以为空
     * @return
     */
    @RequestMapping(value="/{itsmcode}/map/regiondata")
    @ResponseBody
    public List getRegiondata(ModelMap model,@PathVariable String itsmcode,@RequestParam("positionleft") String positionleft,@RequestParam("positionright") String positionright,
                              @RequestParam("project") String project,@RequestParam("date") String date) throws Exception {
        HashMap<String, String> fields = new HashMap<String, String>();
        List<MapStatisticsVO> mapList = new ArrayList<>();
        fields.put("period",date);
        fields.put("project",project);
        fields.put("positionleft",positionleft);
        fields.put("positionright",positionright);
        try{
            RestClientProxy eventRecorderProxy = restClientFactory.getEventRecorderClient();
            if(Objects.nonNull(eventRecorderProxy)){
                ITicketStatisticsQuery iTicketStatisticsQuery = eventRecorderProxy.getService(ITicketStatisticsQuery.class);
                if(Objects.nonNull(iTicketStatisticsQuery)){
                    RestResponse<List<MapStatisticsVO>> mapStatistics= iTicketStatisticsQuery.statisticsByRegion(itsmcode, fields);
                    if(Objects.nonNull(mapStatistics)){
                        mapList =mapStatistics.getResult();
                    }else{
                          log.error("error query mapStatistics list is null");
                    }
                }else{
                    log.error("error no find ITicketStatisticsQuery.class ");
                }
            }else{
                log.error("error EventRecorderProxy interface exception");
            }
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }
        return mapList;
    }
}